import { fetchGetAllMeetingDetail, fetchIsNotExist, fetchPreKey, fetchResources } from '@/api/create'
import { fetchGetMeetingDeadLine } from '@/api/sysConfig/basicConfig'
import MeetingHeader from '@/components/MeetingHeader'
import WebRecommendBrowser from '@/components/WebRecommendBrowser'
import useInit from '@/hooks/useInit'
import { useGlobalStore } from '@/store/global'
import { getUrlParams } from '@/utils'
import { useEffect } from 'react'
import shallow from 'zustand/shallow'
import dayjs from '@/plugins/dayjs'
import { fetchKisCookie, fetchStatus } from '@/api/global'
import CreateContent from './createContent'
import { useCreateContentStore } from './createContent/store'
import { useMeetingParamsStore } from './createContent/blocks/meetingParams/store'
import { useBasicInfoStore } from './createContent/blocks/basicInfo/store'
import { useMeetingPollStore } from './createContent/blocks/poll/store'
import { useMeetingLiveVideoStore } from './createContent/blocks/liveVideo/store'
import { useMeetingMixStore } from './createContent/blocks/mix/store'
import { useMeetingDcsStore } from './createContent/blocks/dcs/store'
import { useMeetingAiStore } from './createContent/blocks/ai/store'
import { Confirm } from '@/components/Alert'
import { transSelectUserItem } from './createContent/blocks/basicInfo/translator'
import { t } from 'i18next'
import { changeMeetingType, initMeetingTypeList } from './createContent/blocks/meetingParams/store.combine'
import { userEdit, userInit } from './createContent/blocks/user/store.combine'
import { Message } from '@kedacom/react-next'
import { useMeetingTVWallStore } from './createContent/blocks/tvwall/store'
import { vipSort2Users } from './createContent/store.combine'
import { initReactVmp } from './createContent/blocks/vmp/store.combine'
import useUnLoad from './createContent/hooks/useUnLoad'

const meetingMoid = getUrlParams('meetingMoid') ?? ''

function App() {
	const { user, userLoaded, serverInfo } = useGlobalStore(
		(state) => ({ user: state.user, userLoaded: state.userLoaded, serverInfo: state.serverInfo }),
		shallow
	)
	const { update } = useCreateContentStore((state) => ({ update: state.update }), shallow)

	useInit()
	useUnLoad()
	useEffect(() => {
		if (!userLoaded) return
		if (!user || !serverInfo) return
		fetchIsNotExist(meetingMoid).then(async (res) => {
			if (!res.success) {
				Confirm(res.description ?? t('操作失败'), () => {
					window.location.href = './meetingList.html'
				})
			} else {
				let m = Message.loading(t('加载中，请稍候……'))

				update({ meetingMoid: meetingMoid, isTemplate: false })
				let deadLine = await fetchGetMeetingDeadLine()
				update({ maxDayForAllowBookMeeting: deadLine })
				//更新权限
				useCreateContentStore.getState().initPermission()
				let _preKey = await fetchPreKey(meetingMoid, 1)
				update({ preKey: _preKey })
				//加载规模信息
				fetchResources().then((res) => {
					if (res.success && res.resources) {
						update({ resources: res.resources })
					}
				})
				if (meetingMoid) {
					// 更新会议
					let _model = await fetchGetAllMeetingDetail(meetingMoid)
					if (!_model) {
						Confirm(t('当前会议已被取消或删除！'), () => {
							window.location.href = './meetingList.html'
						})
						return
					}

					update({ state: _model.state })
					//初始化基本信息
					useBasicInfoStore.getState().init({ isTemplate: false, model: _model })
					//初始化会议参数
					initMeetingTypeList() //更新会议类型列表
					useMeetingParamsStore.getState().init(_model)
					useMeetingPollStore.getState().init(_model.poll) //初始化轮询
					useMeetingMixStore.getState().init(_model.mix) //初始化混音
					useMeetingDcsStore.getState().init(_model.dcs) //初始化数据协作
					useMeetingLiveVideoStore.getState().init(_model.recorder) //初始化直播与录播
					useMeetingAiStore.getState().init(_model.ai) //初始化ai
					initReactVmp(_model.vmp) //初始化vmp
					useMeetingTVWallStore.getState().init(_model.tv_wall)
					//初始化user
					userEdit({
						all: _model.invite_members,
						often: _model.often_mts ?? [],
					})
					vipSort2Users()
				} else {
					// 创建会议
					/**
					 * 通过周视图创建会议
					 * 需要后台配合 + 改逻辑，因为kis已经拿出，直接不会通过searchRoom进界面，
					 * 如果以后会放开，那么需要增加请求，做一个锁定会议室的操作，获取最新的meetingFormKey，
					 * 并且room人员需要直接添加到 user 里去
					 */
					if (getUrlParams('source') === 'searchRoom') {
						let day = getUrlParams('day')
						let startTime = day + ' ' + getUrlParams('startTime')
						let endTime = day + ' ' + getUrlParams('endTime')
						let duration = dayjs(endTime).diff(dayjs(startTime), 'minute')
						let searchMeetingRoom = getUrlParams('searchMeetingRoom') //保留url设置会议搜索规则
						let _meetingCriteriaList: Partial<{
							deviceIds: string
							number: number
							personNumLowerLimit: number
							personNumUpperLimit: number
							regionId: number
							regionName: string
							meetingRoomId: string
						}> | null = searchMeetingRoom ? JSON.parse(decodeURIComponent(searchMeetingRoom)) : null

						useBasicInfoStore.setState({
							day,
							startTime: dayjs(startTime).format('HH:mm'),
							hour: Math.floor(duration / 60),
							minute: duration % 60,
							meetingCriteriaList: _meetingCriteriaList
								? [
										{
											region_name: _meetingCriteriaList.regionName ?? '',
											device_ids: _meetingCriteriaList.deviceIds ?? '',
											num: _meetingCriteriaList.number ?? 0,
											region_id: _meetingCriteriaList.regionId ?? 0,
											up_seating: _meetingCriteriaList.personNumUpperLimit ?? 0,
											down_seating: _meetingCriteriaList.personNumLowerLimit ?? 0,
											meeting_room_id: _meetingCriteriaList.meetingRoomId ?? '0',
										},
								  ]
								: [],
						})
					}
					//初始化基本信息
					useBasicInfoStore.setState({
						name: t('{{- name}}的会议', { name: user.name }),
						manager: transSelectUserItem({
							account: user.moid,
							account_type: 1,
							name: user.name,
						}),
						mobilePhone: user.mobile_phone,
						phoneNO: user.ext_num ? user.ext_num.split('-')?.[2] ?? '' : '',
					})
					useBasicInfoStore.setState({ isInit: false }) //isInit的设置必须在name之后

					//初始化会议参数
					let defaultMeetingType = initMeetingTypeList()
					changeMeetingType(defaultMeetingType)
					useMeetingParamsStore.setState({ sourceUsed: 1, rate: defaultMeetingType === 2 ? 4096 : 2048 }) //新建的情况下传统模式默认资源预占
					useMeetingParamsStore.setState({
						rate:
							defaultMeetingType === 2
								? useCreateContentStore.getState().permission.enableHDMeeting
									? 4096
									: 2048
								: 2048,
					}) //rate未及时更新，先做赋值操作

					useMeetingPollStore.getState().init(null) //初始化轮询
					useMeetingMixStore.getState().init(null) //初始化混音
					useMeetingDcsStore.getState().init(null) //初始化数据协作
					useMeetingLiveVideoStore.getState().init(null) //初始化直播与录播
					useMeetingAiStore.getState().init(null) //初始化ai
					initReactVmp(null) //初始化vmp
					useMeetingTVWallStore.getState().init(null) //初始化vmp
					//初始化user
					userInit({
						user: {
							account: user.moid,
							account_type: 1,
							name: user.name,
							protocol: 255,
							e164: user.e164,
							portrait: user.portrait32,
							bitrate: useMeetingParamsStore.getState().rate,
						},
						rooms: [],
					})
				}
				m.hide()
			}
		})
		const date = serverInfo.system_date
		update({
			systemDateTime: dayjs(date).format('YYYY-MM-DD HH:mm:ss'),
			systemDate: dayjs(date).format('YYYY-MM-DD'),
		})

		if (serverInfo.enable_room && user?.enable_kis && !serverInfo.stand_alone) {
			fetchStatus(() => {
				fetchKisCookie()
			})
		}
	}, [user, serverInfo, userLoaded])

	return (
		<>
			<WebRecommendBrowser />
			<MeetingHeader tabIndex={1} isShowCreateBtn={false} />
			<CreateContent />
		</>
	)
}

export default App
